import { View, Text, Picker, Image } from '@tarojs/components';
import styles from '../index.less';
import { AtImagePicker } from 'taro-ui';
import { useState } from 'react';
import { uploadTempToOSS } from '@/services/oss-upload';

import imageUrl from '@/assets/food-default.png'
import Taro from '@tarojs/taro';

const Common = ({ formData, setFormData }: any) => {
  const handleImageUpload = async () => {
    // 这里可以添加图片上传的逻辑，更新 formData.imageUrl
    // 模拟上传后的结果
    const newImageUrl = 'https://via.placeholder.com/150';
    setFormData((prev: any) => ({ ...prev, imageUrl: newImageUrl }));
  };

  const [files, setFiles] = useState<{ url: string }[]>([]);

  const handleUpload = async (tempPath: string) => {
    try {
      const ossUrl = await uploadTempToOSS(tempPath);
      console.log('上传成功:', ossUrl);
      // 更新 formData.imageUrl
      console.log(files, '此时的files');

      setFiles((prev: any) => [...prev, { url: ossUrl }]);
      setFormData((prev: any) => ({ ...prev, images: [...prev.images, ossUrl] }));
    } catch (error) {
      console.error('上传失败:', error);
      Taro.showToast({
        title: '图片上传失败',
        icon: 'none'
      })
    }
  };

  const onChange = (files, operationType, index) => {
    console.log(files, 'files1--');

    if (operationType === 'add') {
      const newUrl = files[files.length - 1].url;
      handleUpload(newUrl);
    }

    if (operationType === 'remove') {
      setFiles(files);
      const newImages = files.filter((file, i) => i !== index);
      setFormData((prev: any) => ({ ...prev, images: newImages }));
    }

    console.log(files, 'files', operationType, index);

  }
  const onFail = (mes) => {
    console.log(mes)
  }
  // const onImageClick = (index, file) => {
  //   console.log(index, file)
  // }

  return (
    <View>
      <View className={styles.formItem}>
        <Text className={styles.label}>日期</Text>
        <Picker
          mode="date"
          value={formData.date}
          onChange={(e) => setFormData((prev: any) => ({ ...prev, date: e.detail.value }))}
        >
          <View className={styles.picker}>{formData.date}</View>
        </Picker>
      </View>

      <View className={styles.formItem}>
        <Text className={styles.label}>时间</Text>
        <Picker
          mode='time'
          value={formData.time}
          onChange={e => setFormData(prev => ({ ...prev, time: e.detail.value }))}
        >
          <View className={styles.picker}>{formData.time || '请选择时间'}</View>
        </Picker>
      </View>

      <View className={styles.formItem}>
        <Text className={styles.label}>图片</Text>
        <AtImagePicker
          length={3}
          count={6}
          files={files}
          onChange={onChange}
          onFail={onFail}
        // onImageClick={onImageClick}
        />
      </View>
    </View>
  );
};

export { Common };


